package com.ws.controller;

import com.ws.entity.LoginUser;
import com.ws.repository.LoginUserRepository;
import com.ws.request.LoginRequest;
import com.ws.response.LoginResponse;
import com.ws.service.impl.UserDetailsServiceImpl;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：ws
 * @date ：Created in 2023/11/11 23:15
 * @description：TODO
 * @modified By：
 * @version: 1.0.0
 */
@Controller
@RefreshScope
//@CrossOrigin
@RequestMapping("/login")
public class LoginController {
    @Autowired
    UserDetailsService userDetailsService;

    private static final String SECRET_KEY = "HfkjksFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJIJWO";
    private static final long EXPIRATION_TIME = 86400000;

    @GetMapping("")
    public ResponseEntity<LoginResponse> login(@RequestParam(value="username",required=false) String username,
                                               @RequestParam(value="password",required=false) String password ) {
        LoginRequest request = new LoginRequest();
        request.setUsername(username);
        request.setPassword(password);
        // 在这里进行用户名和密码验证，验证通过则生成 Token
        UserDetails user  = userDetailsService.loadUserByUsername(request.getUsername());
        if (user != null && user.getPassword().equals(request.getPassword())) {
            String token = generateToken(user);
            System.out.println("生成的token值为："+token);
            return ResponseEntity.ok(new LoginResponse(token));
        } else {
            return ResponseEntity.ok(new LoginResponse(null));
        }
    }

    private String generateToken(UserDetails user) {
        //生成对应的token
        Map<String, Object> claims = new HashMap<>();
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }


}
